package main

import (
	"fmt"
	"strings"
)

func main() {
	queryIp := "2001:0db8:85a3:0:0:8A2E:0370:7334"
	fmt.Println(validIPAddress(queryIp))
}

func validIPAddress(queryIP string) string {
	if isIPv4(queryIP) {
		return "IPv4"
	}
	if isIPv6(queryIP) {
		return "IPv6"
	}
	return "Neither"
}

func isIPv4(queryIP string) bool {
	items := strings.Split(queryIP, ".")
	if len(items) != 4 {
		return false
	}
	for _, item := range items {
		sum := 0
		if len(item) == 0 || len(item) > 3 ||
			(len(item) > 1 && item[0] == '0') { //不能有前导0
			return false
		}
		for _, ch := range []rune(item) {
			if !isDigit(ch) {
				return false
			}
			sum = sum*10 + int(ch-'0')
		}
		if sum < 0 || sum > 255 {
			return false
		}
	}
	return true
}

func isIPv6(queryIP string) bool {
	items := strings.Split(queryIP, ":")
	if len(items) != 8 {
		return false
	}
	for _, item := range items {
		if len(item) == 0 || len(item) > 4 { //不能有前导0
			return false
		}
		for _, ch := range []rune(item) {
			if !isHexLetter(ch) {
				return false
			}
		}
	}
	return true
}

func isDigit(ch rune) bool {
	return ch >= '0' && ch <= '9'
}

func isHexLetter(ch rune) bool {
	return (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F') || isDigit(ch)
}
